var express = require('express');
var router = express.Router();


var db = require('../model/index')

/* GET users listing. */
router.get('/', (req, res, next) => {
  let page = (req.query.page - 1) * 10
  let page_max = req.query.page * 10
  let mysql = `SELECT * FROM managers ORDER BY manager_name DESC LIMIT ?,?`
  db(mysql, [page, page_max], (err, data) => {
    if (err) {
      return res.json({
        state: 500,
        message: '数据库操作失败，请稍后重试',
      })
    }

    res.json({
      state: 200,
      message: '数据库操作成功',
      data: data
    })
  })
});

/* 获取页码. */
router.get('/pagetotal', (req, res, next) => {

  let mysql = `SELECT * FROM managers;`
  db(mysql, [], (err, data) => {
    if (err) {
      return res.json({
        state: 500,
        message: '数据库操作失败，请稍后重试',
      })
    }

    res.json({
      state: 200,
      message: '数据库操作成功',
      data: data
    })
  })
});


/* 增 */
router.post('/add', (req, res, next) => {

  let mysql = `INSERT INTO managers(manager_name,manager_sex,manager_idCard,manager_job,manager_address,manager_role,manager_email,manager_phone,manager_password,manager_accout) VALUES(?,?,?,?,?,?,?,?,'123456',?)`
  db(mysql, [req.query.manager_name, 
            req.query.manager_sex, 
            req.query.manager_idCard, 
            req.query.manager_job, 
            req.query.manager_address, 
            req.query.manager_role, 
            req.query.manager_email, 
            req.query.manager_phone, 
            req.query.manager_phone], (err, data) => {

    if (err) {
      return res.json({
        state: 500,
        message: '数据库操作失败，请稍后重试',
      })
    }

    res.json({
      state: 200,
      message: '添加管理员成功'
    })
  })
});

// 重置密码
router.put('/repassword', (req, res, next) => {

  let id = req.query.manager_id
  let mysql = `UPDATE managers SET manager_password="123456" WHERE manager_id=?`
  db(mysql, [id], (err, data) => {

    if (err) {
      return res.json({
        state: 500,
        message: '数据库操作失败，请稍后重试',
      })
    }

    res.json({
      state: 200,
      message: '修改成功,密码重置为123456！'
    })
  })
});

/* GET users listing. */
router.delete('/delete', (req, res, next) => {
  let mysql = `DELETE FROM managers WHERE manager_id=?`
  db(mysql, [req.query.manager_id], (err, data) => {
    if (err) {
      return res.json({
        state: 500,
        message: '数据库操作失败，请稍后重试',
      })
    }

    res.json({
      state: 200,
      message: '数据库删除成功'
    })
  })
});

module.exports = router;